// pages/userGoEvaluate/userGoEvaluate.js
import api from '../../utils/api.js'
import { config } from '../../utils/config'
import {
    HTTP
} from '../../utils/http.js'
const http = new HTTP()
const user_id = wx.getStorageSync("user_id");
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        images: [], //微信 本地 图片路径
        onLineimages: [], // 服务器返回的线上 图片路径
        content: '', //用户的评论
        evaluateShopInfo: [], // 当前 评***价的店铺信息
        starOn: "{{imgUrl}}/images/shopStar-on@2x.png",
        starOff: "{{imgUrl}}/images/shopStar-off@2x.png",
        flag: 5, //默认5星评***价
        word: ['很差', '不好', '一般', '很好', '极好'],
        starDec: '极好', //默认 星级对应的描述
        labels: [{
                name: '分量足',
                checked: false,
                id: 0
            },
            {
                name: '包装完整',
                checked: false,
                id: 1
            },
            {
                name: '味道鲜美',
                checked: false,
                id: 2
            },
            {
                name: '价格便宜',
                checked: false,
                id: 3
            },
            {
                name: '很新鲜',
                checked: false,
                id: 4
            },
            {
                name: '食材干净',
                checked: false,
                id: 5
            }
        ],
        anonym: [{
            value: '匿名评***价',
            checked: false,
            id: 0
        }],
        imgUrl: config.imgUrl,
        addPicState: true //图片大于4张，隐藏按钮
    },
    submit(e) { //提交评***价
        let evaluateShopInfo = this.data.evaluateShopInfo; //当前 在评***价的店铺的信息
        let images = this.data.images;
        let onLineimages = this.data.onLineimages; //线上 图片 路径
        let content = this.data.content; // 拿到评论
        let grade = this.data.flag * 2; //拿到评分
        let bought = this.data.bought;
        //
        let count = 0; //本地图片计数
        console.log('evaluateShopInfo', evaluateShopInfo)
            //默认评论
        if (content == '') {
            content = '菜品新鲜，包装好，推荐给大家'
        }
        //默认店铺标签，无,拿到 处理过后选中的label标签
        let label = this.handleLabel();
        // 获取 用户是否 点击匿名
        let anonym = this.handleAnonym();


        if (images.length) {
            // 先上传图片
            wx.showToast({
                title: '正在上传图片...',
                icon: 'loading',
                mask: true,
                duration: 1500
            })
            for (let i = 0, h = images.length; i < h; i++) {
                console.log('images', images[i])
                    //上传文件
                wx.uploadFile({
                    url: "https://xiangtws.com/public/index.php/api/Status/uploadImages",
                    filePath: images[i],
                    name: 'images[]', //与后台 命名的数组对应
                    success: (res) => {
                        console.log(res)
                        onLineimages.push(res.data)
                        this.setData({
                            onLineimages
                        })
                        count++;
                        //如果是最后一张,则隐藏等待中  
                        if (count == images.length) {
                            wx.hideToast();
                            console.log('count', count)
                            let data = {
                                id: user_id, //  用户ID
                                oid: evaluateShopInfo.id, //  订单ID
                                shopid: evaluateShopInfo.shop_id, //  商户ID
                                label: label, //  标签
                                images: this.data.onLineimages, //  上传到服务器之后，返回的图片路径
                                content: content, //评论
                                grade: grade, //  评分
                                anonym: anonym, // 是否匿名 1不匿名2匿名
                                bought: bought //已购买
                            }

                            http.request({
                                url: "/status/userAppraise",
                                data: data,
                                success: (res) => {
                                    console.log(2222222, res)
                                    wx.showToast({
                                        title: '评***价上传成功',
                                        icon: 'success',
                                        duration: 1500,
                                        mask: true,
                                        success: () => {
                                            let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
                                            let prevPage = pages[pages.length - 2];
                                            prevPage.setData({
                                                evaluateData: data
                                            })

                                            setTimeout(function() {
                                                wx.navigateBack({

                                                })
                                            }, 1500);
                                        }
                                    })
                                }
                            })
                        }
                    },
                    fail: function(res) {
                        wx.hideToast();
                        wx.showModal({
                            title: '错误提示',
                            content: '上传图片失败',
                            showCancel: false,
                            success: function(res) {}
                        })
                    }
                });


            }
        } else { //用户 没有上传图片，直接 评***价

            let data = {
                id: user_id, //  用户ID
                oid: evaluateShopInfo.id, //  订单ID
                shopid: evaluateShopInfo.shop_id, //  商户ID
                label: label, //  标签
                images: this.data.onLineimages, //  上传到服务器之后，返回的图片路径
                content: content, //评论
                grade: grade, //  评分
                anonym: anonym, // 是否匿名 1不匿名2匿名
                bought: bought //已购买
            }

            http.request({
                url: api.userAppraise,
                data: data,
                success: (res) => {
                    console.log(2222222, res)
                    let pages = getCurrentPages();
                    console.log('pages', pages)
                    wx.showToast({
                        title: '评***价上传成功',
                        icon: 'success',
                        duration: 1500,
                        mask: true,
                        success: () => {

                            let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
                            let prevPage = pages[pages.length - 2];
                            prevPage.setData({
                                evaluateData: data
                            })

                            setTimeout(function() {
                                wx.navigateBack({
                                        delta: 1 // 返回上一级页面。
                                    })
                                    //  wx.redirectTo({
                                    //    url: "/pages/myAllOrderList/myAllOrderList",
                                    //  })
                            }, 1500);
                        }
                    })
                }
            })
        }



    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        let evaluateShopInfo = wx.getStorageSync('evaluateShopInfo')
        if (evaluateShopInfo) {
            this.setData({
                evaluateShopInfo
            })
        };
        // 菜谱类型评***价
        if (evaluateShopInfo.type == 1) {
            let snap_items = evaluateShopInfo.snap_items
            let bought = []
            for (let key in snap_items) {
                bought.push(snap_items[key].cook_book_name)
            }
            this.setData({
                bought
            })
        } else if (evaluateShopInfo.type == 0) { //单品类型
            let snap_items = evaluateShopInfo.snap_items
            let bought = []

            snap_items.forEach((ele) => {
                bought.push(ele.product_name)
            })
            this.setData({
                bought
            })
        }

    },
    chooseImage(e) {
        let that = this
        let images = that.data.images
            // 选择图片
        wx.chooseImage({
                count: 4 - images.length,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: function(res) {
                    var tempFilePaths = res.tempFilePaths
                    if (images.length > 3) {
                        wx.showToast({
                            title: '最多上传4张',
                            mask: true,
                        })
                        return false;
                    } else {
                        console.log('tempFilePaths', tempFilePaths)
                        images.push(tempFilePaths[0])
                        that.setData({
                            images: images
                        });
                    }


                }
            })
            //上传 图片大于4张时，隐藏按钮
        if (images.length >= 3) {
            console.log(222222)
            this.setData({
                addPicState: false
            })
        }
    },
    deleteImage(e) {
        let images = this.data.images;
        let index = e.currentTarget.dataset.index;
        images.splice(index, 1);
        //只要删除图片，就会出现上传按钮
        this.setData({
            images,
            addPicState: true
        });

    },
    previewImg(e) {
        let index = e.currentTarget.dataset.index;
        let images = this.data.images;
        wx.previewImage({
            current: images[index],
            urls: images
        })
    },
    //用户输入的评***价
    enterContent: function(e) {
        let value = e.detail.value;
        let length = parseInt(value.length);
        this.setData({
            content: value
        });

    },

    // 星级评***价 操作
    changeStar1(e) {
        let i = e.currentTarget.dataset.star;
        let starDec = this.data.word[i - 1]
        this.setData({
            flag: 1,
            starDec
        })
    },
    changeStar2(e) {
        let i = e.currentTarget.dataset.star;
        let starDec = this.data.word[i - 1]
        this.setData({
            flag: 2,
            starDec
        })
    },
    changeStar3(e) {
        let i = e.currentTarget.dataset.star;
        let starDec = this.data.word[i - 1]
        this.setData({
            flag: 3,
            starDec
        })
    },
    changeStar4(e) {
        let i = e.currentTarget.dataset.star;
        let starDec = this.data.word[i - 1]
        this.setData({
            flag: 4,
            starDec
        })
    },
    changeStar5(e) {
        let i = e.currentTarget.dataset.star;
        let starDec = this.data.word[i - 1]
        this.setData({
            flag: 5,
            starDec
        })
    },

    // 店铺 描述标签，点击切换选中
    checkedLabel(e) {
        console.log(e)
        let lindex = e.target.dataset.lindex;
        let labels = this.data.labels;
        labels[lindex].checked = !labels[lindex].checked
        this.setData({
            labels
        })
    },
    // 处理用户选中的标签，上传
    handleLabel() {
        let onLineLabel = [];
        let labels = this.data.labels;
        labels = labels.filter((ele) => {
            return ele.checked == true
        })

        labels.forEach((ele) => {
            onLineLabel.push(ele.name)
        })
        console.log('onLineLabel', onLineLabel)
        let label = onLineLabel.join(' | ')
        console.log('label', label)
        return label
    },
    // 匿名评***价 点击
    checkboxChange(e) {
        console.log(e)
        let anonym = this.data.anonym;
        anonym[0].checked = !anonym[0].checked;
        this.setData({
            anonym
        })
    },
    // 用户 点击 匿名评***价的处理
    handleAnonym() {
        let anonym = this.data.anonym[0];
        if (anonym.checked == true) {
            return 2; //1不匿名2匿名
        } else {
            return 1
        }
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        wx.removeStorageSync('evaluateShopInfo')
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    }
})